package com.jf3q.admin.controller;

import com.aliyun.teautil.Common;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod20170321.models.GetVideoPlayAuthResponse;
import com.jf3q.admin.service.impl.CourseServiceImpl;
import com.jf3q.admin.service.impl.VideoServiceImpl;
import com.jf3q.admin.utils.vo.AjaxResultVO;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduVideo;
import com.jf3q.common.sample.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author ASUS
 * @date 2024/4/16
 * @apiNote
 */
@RestController
@RequestMapping("/video")
public class VideoController {

    @Autowired
    VideoServiceImpl videoService;

    @Autowired
    Sample sample;


    @GetMapping("/getById/{id}")
    public AjaxResultVO toUpdate(@PathVariable String id) {
        return AjaxResultVO.success(videoService.getById(id));
    }

    @PostMapping("/saveOrUpdate")
    public AjaxResultVO saveOrUpdate(@RequestBody EduVideo chapter) {
        return videoService.saveOrUpdate(chapter) ? AjaxResultVO.success() : AjaxResultVO.error();
    }

    @GetMapping("/delete/{id}")
    public AjaxResultVO delete(@PathVariable String id) throws Exception {
        EduVideo video = videoService.getById(id);

        com.aliyun.vod20170321.Client client = sample.createClient();
        com.aliyun.vod20170321.models.DeleteVideoRequest deleteVideoRequest = new com.aliyun.vod20170321.models.DeleteVideoRequest();
        deleteVideoRequest.setVideoIds(video.getVideoSourceId());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        client.deleteVideoWithOptions(deleteVideoRequest,runtime);

        return videoService.removeById(video) ? AjaxResultVO.success() : AjaxResultVO.error();
    }


    @GetMapping("/getPlayAuth/{id}")
    public AjaxResultVO getPlayAuth(@PathVariable String id) throws Exception {
        com.aliyun.vod20170321.Client client = sample.createClient();
        com.aliyun.vod20170321.models.GetVideoPlayAuthRequest getVideoPlayAuthRequest = new com.aliyun.vod20170321.models.GetVideoPlayAuthRequest()
                .setVideoId(id);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            GetVideoPlayAuthResponse response = client.getVideoPlayAuthWithOptions(getVideoPlayAuthRequest, runtime);
            com.aliyun.teaconsole.Client.log(Common.toJSONString(response));

            return AjaxResultVO.success(response.getBody().getPlayAuth());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return AjaxResultVO.error(e.getMessage());
        }
    }


    @GetMapping("/getPlayUrl/{id}")
    public AjaxResultVO getPlayUrl(@PathVariable String id) throws Exception {
        com.aliyun.vod20170321.Client client = sample.createClient();
        com.aliyun.vod20170321.models.GetPlayInfoRequest getPlayInfoRequest = new com.aliyun.vod20170321.models.GetPlayInfoRequest()
                .setVideoId(id);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.vod20170321.models.GetPlayInfoResponse resp = client.getPlayInfoWithOptions(getPlayInfoRequest, runtime);
            com.aliyun.teaconsole.Client.log(Common.toJSONString(resp));
            String playURL = resp.getBody().getPlayInfoList().getPlayInfo().get(0).getPlayURL();
            return AjaxResultVO.success(playURL);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return AjaxResultVO.error(e.getMessage());
        }
    }

    @Autowired
    CourseServiceImpl courseService;


    @PostMapping("/upload/{courseId}")
    public AjaxResultVO testUploadVideo(@PathVariable String courseId, MultipartFile file) throws IOException {
        String title = file.getOriginalFilename();
        String suffix = title.substring(title.lastIndexOf("."));
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String dataPath = format.format(new Date());

        String fileName = dataPath + "/" + UUID.randomUUID().toString().replace("-", "") + suffix;


        UploadStreamRequest request = new UploadStreamRequest(sample.accesskeyId,sample.secretAccesskey, title, fileName, file.getInputStream());

        request.setCateId(1000590215L);

        EduCourse byId = courseService.getById(courseId);
        request.setCoverURL(byId.getCover());
        request.setTemplateGroupId("b456f2129e9b293c0b8b767902a845b4");

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            return AjaxResultVO.success(response.getVideoId());
        } else {
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
            return AjaxResultVO.error(response.getMessage());
        }
    }


}
